<?php
class ModelSaleOrder extends Model {
	public function getexportOrders($data = array()) {
		require_once DIR_SYSTEM . 'phpexcel/Classes/PHPExcel.php';

		// Create new PHPExcel object
		//echo date('H:i:s') , " Create new PHPExcel object" , EOL;//die;
		ini_set('display_errors', 1);
		ini_set('log_errors', 1);
		error_reporting(E_ALL);
		ini_set("memory_limit","-1");
		set_time_limit(0);
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getActiveSheet()->setTitle();
		$results= array();
		foreach($data as $order_id){
			$order_query = $this->db->query("SELECT *, (SELECT CONCAT(c.firstname, ' ', c.lastname) FROM " . DB_PREFIX . "customer c WHERE c.customer_id = o.customer_id) AS customer, (SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'");

			if ($order_query->num_rows) {
				$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");

				if ($country_query->num_rows) {
					$payment_iso_code_2 = $country_query->row['iso_code_2'];
					$payment_iso_code_3 = $country_query->row['iso_code_3'];
				} else {
					$payment_iso_code_2 = '';
					$payment_iso_code_3 = '';
				}

				$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");

				if ($zone_query->num_rows) {
					$payment_zone_code = $zone_query->row['code'];
				} else {
					$payment_zone_code = '';
				}

				$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");

				if ($country_query->num_rows) {
					$shipping_iso_code_2 = $country_query->row['iso_code_2'];
					$shipping_iso_code_3 = $country_query->row['iso_code_3'];
				} else {
					$shipping_iso_code_2 = '';
					$shipping_iso_code_3 = '';
				}

				$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");

				if ($zone_query->num_rows) {
					$shipping_zone_code = $zone_query->row['code'];
				} else {
					$shipping_zone_code = '';
				}

				$reward = 0;

				$order_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

				foreach ($order_product_query->rows as $product) {
					$reward += $product['reward'];
				}
				//ip telephone
				
				$order_ip_telephone = $this->db->query("SELECT * FROM " . DB_PREFIX . "backlist_ipphone WHERE ip = '" . $order_query->row['ip'] . "' OR telephone='" . $order_query->row['telephone'] . "'");

				if ($order_ip_telephone->num_rows) {
					$blacklist = '黑名单';
				} else {
					$blacklist = '否';
				}
				//$option_data = array();
				$option_data ='';

				$options = $this->getOrderOptions($order_id, $product['order_product_id']);
				
				
				foreach ($options as $option) {
					if ($option['type'] != 'file') {
						// $option_data[] = array(
							// 'name'  => $option['name'],
							// 'value' => $option['value'],
							// 'type'  => $option['type']
						// );
						$option_data.= $option['name'].':'.$option['value'].'  ';
					} 
				}

				// $data['products'][] = array(
					// 'order_product_id' => $product['order_product_id'],
					// 'product_id'       => $product['product_id'],
					// 'name'    	 	   => $product['name'],
					// 'model'    		   => $product['model'],
					// 'option'   		   => $option_data,
					// 'quantity'		   => $product['quantity'],
					// 'price'    		   => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
					// 'total'    		   => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
					// 'href'     		   => $this->url->link('catalog/product/edit', 'user_token=' . $this->session->data['user_token'] . '&product_id=' . $product['product_id'], true)
				// );
				
				$this->load->model('customer/customer');

				$affiliate_info = $this->model_customer_customer->getCustomer($order_query->row['affiliate_id']);

				if ($affiliate_info) {
					$affiliate_firstname = $affiliate_info['firstname'];
					$affiliate_lastname = $affiliate_info['lastname'];
				} else {
					$affiliate_firstname = '';
					$affiliate_lastname = '';
				}

				$this->load->model('localisation/language');

				$language_info = $this->model_localisation_language->getLanguage($order_query->row['language_id']);

				if ($language_info) {
					$language_code = $language_info['code'];
				} else {
					$language_code = $this->config->get('config_language');
				}
				
				list($msec, $sec) = explode(' ', microtime());
				$msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
				// $time=microtime();
				$time=substr($msectime,2);

				$results[]= array(
					'订单号'                => (string)('O'.$order_query->row['order_id'].$time),
					'属性'                    => $option_data,
					'数量'                    => $product['quantity'],
					'单价'                    => $product['price'],
					'产品型号'                => $product['model'],
					'产品标识'                => $product['product_marking'],
					// 'invoice_no'              => $order_query->row['invoice_no'],
					// 'invoice_prefix'          => $order_query->row['invoice_prefix'],
					// 'customer_id'             => $order_query->row['customer_id'],
					// 'customer'                => $order_query->row['customer'],
					// 'customer_group_id'       => $order_query->row['customer_group_id'],
					// '网站地址'               => $order_query->row['store_url'],
					'姓'               => $order_query->row['firstname'],
					'名'                => $order_query->row['lastname'],
					'邮箱'                   => $order_query->row['email'],
					'电话'               => $order_query->row['telephone'],
					'shipping_firstname'      => $order_query->row['shipping_firstname'],
					'shipping_lastname'       => $order_query->row['shipping_lastname'],
					// 'shipping_company'        => $order_query->row['shipping_company'],
					'详细地址'      => $order_query->row['shipping_address_1'],
					// 'shipping_address_2'      => $order_query->row['shipping_address_2'],
					'邮编'       => $order_query->row['shipping_postcode'],
					'地区'        => '台湾',
					'市'          => $order_query->row['shipping_country'],
					'市区'             => $order_query->row['shipping_zone'],
					'shipping_iso_code_2'     => $shipping_iso_code_2,
					'shipping_iso_code_3'     => $shipping_iso_code_3,
					'shipping_address_format' => $order_query->row['shipping_address_format'],
					'运输方式'         => $order_query->row['shipping_method'],
					// 'shipping_code'           => $order_query->row['shipping_code'],
					'客户留言'                 => $order_query->row['comment'],
					'总额'                   => $order_query->row['total'],
					'order_status_id'         => $order_query->row['order_status_id'],
					'订单状态'            => $order_query->row['order_status'],
					// 'affiliate_id'            => $order_query->row['affiliate_id'],
					// 'affiliate_firstname'     => $affiliate_firstname,
					// 'affiliate_lastname'      => $affiliate_lastname,
					'commission'              => $order_query->row['commission'],
					'language_id'             => $order_query->row['language_id'],
					'language_code'           => $language_code,
					'currency_id'             => $order_query->row['currency_id'],
					'currency_code'           => $order_query->row['currency_code'],
					'currency_value'          => $order_query->row['currency_value'],
					'ip'                      => $order_query->row['ip'],
					'是否黑名单'                      => $blacklist,
					'forwarded_ip'            => $order_query->row['forwarded_ip'],
					'user_agent'              => $order_query->row['user_agent'],
					'accept_language'         => $order_query->row['accept_language'],
					'订单生成时间'              => $order_query->row['date_added'],
					'修改时间'           => $order_query->row['date_modified']
				);
			}
		}
		
		$structure= $results[0];
		$columns = [];
		if($structure)
		{
			$col = 'A';
			$col_no = 0;
			foreach($structure as $k=> $field )
			{
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.'1',$k);
				array_push($columns,$k);
				$col_no++;
				$col++;
			}
			//echo "<br>";
		}
		$total_columns = $col_no-1;
		$i=2;
		if($results)
		{
			foreach($results as $key=> $val )
			{
				// var_dump($result);
				$col_no = 0;
				$col = 'A';
				// //echo $total_columns;
				// while($col_no <= $total_columns)
				while($col_no <= $total_columns)
				{
					// //echo "DD<br>";
					// var_dump($columns);
					// //echo $columns[$col_no];
					// //echo $col_no;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($col.$i,$val[$columns[$col_no]]);
					$col++;
					$col_no++;
				}
				// $objPHPExcel->setActiveSheetIndex(0)
				// ->setCellValue('A'.$i,$result['id'])
				// ->setCellValue('B'.$i,$result['title'])
				// ->setCellValue('C'.$i,$result['details'])
				// ->setCellValue('D'.$i,$result['topicId'])
				// ->setCellValue('E'.$i,$result['ques_level'])
				// ->setCellValue('F'.$i,$result['ques_type']);
				$i++;
			}
		}


			

		 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');


		$xx='订单导出'.date("Y-m-d");
		header("Pragma: public");
		header("Expires: 0");
		header("Content-Type: text/html;charset=utf8");

		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-execl");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");;
		header('Content-Disposition:attachment;filename='.$xx.'.xlsx');  
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
		die;
	}
	
	public function getStatisticsOrders() {
		 $statistics_query = $this->db->query("select date_format( o.date_added, '%Y-%m-%d' ) as 'date',count(o.order_id)  as 'subtotal',
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.cause_invalidity='有效订单' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'effective', 
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.order_status_id='17' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'signed' ,
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.order_status_id='18' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'purchase', 
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.order_status_id='19' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'tosend' ,
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.order_status_id='20' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'designated' ,
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.order_status_id='23' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'shipped' ,
												(select count(oc.cause_invalidity)  from  " . DB_PREFIX . "order oc WHERE  date_format( oc.date_added, '%Y-%m-%d' )=date_format( o.date_added, '%Y-%m-%d' ) AND oc.order_status_id='21' GROUP BY  date_format( oc.date_added, '%Y-%m-%d' )) as 'rejection' 
												from  " . DB_PREFIX . "order o GROUP BY  date_format( o.date_added, '%Y-%m-%d' ) ORDER BY date_format( o.date_added, '%Y-%m-%d' ) DESC");
	    
		return  $statistics_query->rows;
	}
	public function getOrder($order_id) {
		$order_query = $this->db->query("SELECT *, (SELECT CONCAT(c.firstname, ' ', c.lastname) FROM " . DB_PREFIX . "customer c WHERE c.customer_id = o.customer_id) AS customer, (SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status FROM `" . DB_PREFIX . "order` o WHERE o.order_id = '" . (int)$order_id . "'");

		if ($order_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");

			if ($country_query->num_rows) {
				$payment_iso_code_2 = $country_query->row['iso_code_2'];
				$payment_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$payment_iso_code_2 = '';
				$payment_iso_code_3 = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");

			if ($zone_query->num_rows) {
				$payment_zone_code = $zone_query->row['code'];
			} else {
				$payment_zone_code = '';
			}

			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");

			if ($country_query->num_rows) {
				$shipping_iso_code_2 = $country_query->row['iso_code_2'];
				$shipping_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$shipping_iso_code_2 = '';
				$shipping_iso_code_3 = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");

			if ($zone_query->num_rows) {
				$shipping_zone_code = $zone_query->row['code'];
			} else {
				$shipping_zone_code = '';
			}

			$reward = 0;

			$order_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

			foreach ($order_product_query->rows as $product) {
				$reward += $product['reward'];
			}
			
			$this->load->model('customer/customer');

			$affiliate_info = $this->model_customer_customer->getCustomer($order_query->row['affiliate_id']);

			if ($affiliate_info) {
				$affiliate_firstname = $affiliate_info['firstname'];
				$affiliate_lastname = $affiliate_info['lastname'];
			} else {
				$affiliate_firstname = '';
				$affiliate_lastname = '';
			}

			$this->load->model('localisation/language');

			$language_info = $this->model_localisation_language->getLanguage($order_query->row['language_id']);

			if ($language_info) {
				$language_code = $language_info['code'];
			} else {
				$language_code = $this->config->get('config_language');
			}

			return array(
				'order_id'                => $order_query->row['order_id'],
				'invoice_no'              => $order_query->row['invoice_no'],
				'invoice_prefix'          => $order_query->row['invoice_prefix'],
				'store_id'                => $order_query->row['store_id'],
				'store_name'              => $order_query->row['store_name'],
				'store_url'               => $order_query->row['store_url'],
				'customer_id'             => $order_query->row['customer_id'],
				'customer'                => $order_query->row['customer'],
				'customer_group_id'       => $order_query->row['customer_group_id'],
				'firstname'               => $order_query->row['firstname'],
				'lastname'                => $order_query->row['lastname'],
				'email'                   => $order_query->row['email'],
				'telephone'               => $order_query->row['telephone'],
				'custom_field'            => json_decode($order_query->row['custom_field'], true),
				'payment_firstname'       => $order_query->row['payment_firstname'],
				'payment_lastname'        => $order_query->row['payment_lastname'],
				'payment_company'         => $order_query->row['payment_company'],
				'payment_address_1'       => $order_query->row['payment_address_1'],
				'payment_address_2'       => $order_query->row['payment_address_2'],
				'payment_postcode'        => $order_query->row['payment_postcode'],
				'payment_city'            => $order_query->row['payment_city'],
				'payment_zone_id'         => $order_query->row['payment_zone_id'],
				'payment_zone'            => $order_query->row['payment_zone'],
				'payment_zone_code'       => $payment_zone_code,
				'payment_country_id'      => $order_query->row['payment_country_id'],
				'payment_country'         => $order_query->row['payment_country'],
				'payment_iso_code_2'      => $payment_iso_code_2,
				'payment_iso_code_3'      => $payment_iso_code_3,
				'payment_address_format'  => $order_query->row['payment_address_format'],
				'payment_custom_field'    => json_decode($order_query->row['payment_custom_field'], true),
				'payment_method'          => $order_query->row['payment_method'],
				'payment_code'            => $order_query->row['payment_code'],
				'shipping_firstname'      => $order_query->row['shipping_firstname'],
				'shipping_lastname'       => $order_query->row['shipping_lastname'],
				'shipping_company'        => $order_query->row['shipping_company'],
				'shipping_address_1'      => $order_query->row['shipping_address_1'],
				'shipping_address_2'      => $order_query->row['shipping_address_2'],
				'shipping_postcode'       => $order_query->row['shipping_postcode'],
				'shipping_city'           => $order_query->row['shipping_city'],
				'shipping_zone_id'        => $order_query->row['shipping_zone_id'],
				'shipping_zone'           => $order_query->row['shipping_zone'],
				'shipping_zone_code'      => $shipping_zone_code,
				'shipping_country_id'     => $order_query->row['shipping_country_id'],
				'shipping_country'        => $order_query->row['shipping_country'],
				'shipping_iso_code_2'     => $shipping_iso_code_2,
				'shipping_iso_code_3'     => $shipping_iso_code_3,
				'shipping_address_format' => $order_query->row['shipping_address_format'],
				'shipping_custom_field'   => json_decode($order_query->row['shipping_custom_field'], true),
				'shipping_method'         => $order_query->row['shipping_method'],
				'shipping_code'           => $order_query->row['shipping_code'],
				'comment'                 => $order_query->row['comment'],
				'total'                   => $order_query->row['total'],
				'reward'                  => $reward,
				'order_status_id'         => $order_query->row['order_status_id'],
				'order_status'            => $order_query->row['order_status'],
				'affiliate_id'            => $order_query->row['affiliate_id'],
				'affiliate_firstname'     => $affiliate_firstname,
				'affiliate_lastname'      => $affiliate_lastname,
				'commission'              => $order_query->row['commission'],
				'language_id'             => $order_query->row['language_id'],
				'language_code'           => $language_code,
				'currency_id'             => $order_query->row['currency_id'],
				'currency_code'           => $order_query->row['currency_code'],
				'currency_value'          => $order_query->row['currency_value'],
				'ip'                      => $order_query->row['ip'],
				'forwarded_ip'            => $order_query->row['forwarded_ip'],
				'user_agent'              => $order_query->row['user_agent'],
				'accept_language'         => $order_query->row['accept_language'],
				'date_added'              => $order_query->row['date_added'],
				'date_modified'           => $order_query->row['date_modified']
			);
		} else {
			return;
		}
	}
	
	
	public function getexportOrdersid($from,$to) {
		
		// $from=
		// $to=
		$sql = "SELECT o.order_id FROM `" . DB_PREFIX . "order` o WHERE date_added BETWEEN '$from' AND '$to' AND order_status_id>0";

		

		$query = $this->db->query($sql);

		return $query->rows;
	}
	
	
	
	public function getOrderAttribute($order_number) {
		$order_query = $this->db->query("SELECT name,value FROM `" . DB_PREFIX . "order_option` op WHERE op.order_id = '" . $order_number . "'");
        if ($order_query->rows) {
			return $order_query->rows;
		}
		
	}
	
    // order_status
	public function getOrders($data = array()) {
		$sql = "SELECT o.order_id,o.payment_zone,o.payment_city,o.cause_invalidity,o.remark,o.payment_address_1,o.store_url,o.email,o.telephone,o.payment_address_1,o.firstname,o.payment_country,o.ip,o.comment,o.total,o.order_status_id, CONCAT(o.firstname, ' ', o.lastname) AS customer, (SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status,(SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.cause_invalidity AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS cause_invalidity_name, o.shipping_code, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id > '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}
		
		if (!empty($data['telephone'])) {
			$sql .= " AND o.telephone = '" . $data['telephone'] . "'";
		}
		
		if (!empty($data['email'])) {
			$sql .= " AND o.email = '" . $data['email'] . "'";
		}

		$sort_data = array(
			'o.order_id',
			'customer',
			'order_status',
			'o.date_added',
			'o.date_modified',
			'o.total'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY o.order_id";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}
		$query = $this->db->query($sql);

		return $query->rows;
	}

	// order_status
	public function getOrdersclick($data = array()) {
		$sql = "SELECT o.order_id,o.payment_zone,o.payment_city,o.cause_invalidity,o.remark,o.payment_address_1,o.store_url,o.email,o.telephone,o.payment_address_1,o.firstname,o.payment_country,o.ip,o.comment,o.total,o.order_status_id, CONCAT(o.firstname, ' ', o.lastname) AS customer, (SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS order_status,(SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.cause_invalidity AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS cause_invalidity_name, o.shipping_code, o.total, o.currency_code, o.currency_value, o.date_added, o.date_modified FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id > '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}
		
		if (!empty($data['telephone'])) {
			$sql .= " AND o.telephone = '" . $data['telephone'] . "'";
		}
		
		if (!empty($data['email'])) {
			$sql .= " AND o.email = '" . $data['email'] . "'";
		}

		$sort_data = array(
			'o.order_id',
			'customer',
			'order_status',
			'o.date_added',
			'o.date_modified',
			'o.total'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY o.order_id";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " DESC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			// $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}
		$query = $this->db->query($sql);
		
		

		return $query->rows;
	}
	
	public function setbacklistiptele($ip,$telephone) {
		$selectsql="SELECT `id`, `customer_id`, `ip`, `date_added`, `status`, `telephone` FROM `oc_backlist_ipphone` WHERE ip='".$ip."' AND telephone='".$telephone."'";
		$query1 = $this->db->query($selectsql);
		// $query1->rows;
		if (!$query1->num_rows) {
			$sql="INSERT INTO `oc_backlist_ipphone`(`customer_id`, `ip`, `date_added`, `status`, `telephone`) VALUES (0,'".$ip."',now(),1,'".$telephone."')";
			$query = $this->db->query($sql);
	  	     return $query;
		}else{
			return 'jtj';
			
		}
		
	   	
		
	}
	
	public function getblacklistip($data = array()) {
		$sql="SELECT ip FROM `" . DB_PREFIX . "backlist_ipphone` WHERE status=1 GROUP BY IP";
		$query = $this->db->query($sql);
		$ip=array();
		foreach($query->rows as $ipaddes){
			$ip[]=$ipaddes['ip'];
		}
	  	return $ip;
		
	}
	
	public function getblacklisttelephone($data = array()) {
		$sql="SELECT telephone FROM `" . DB_PREFIX . "backlist_ipphone` WHERE status=1 GROUP BY telephone";
		$query = $this->db->query($sql);
	  	$telephone=array();
		foreach($query->rows as $telephones){
			$telephone[]=$telephones['telephone'];
		}
	  	return $telephone;
		
	}
	
	public function getrepeatipOrders($data = array()) {
		$sql = "SELECT count(*) as num,ip FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id >= '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_number = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}

		

			$sql .= "  GROUP BY ip HAVING num > 1";
		
		$query = $this->db->query($sql);

		return $query->rows;
	}
	
	public function getrepeataddOrders($data = array()) {
		$sql = "SELECT count(*) as num,payment_address_1 FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id >= '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_number = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}

		

			$sql .= " GROUP BY payment_address_1 HAVING num > 1";
		
		$query = $this->db->query($sql);

		return $query->rows;
	}
	
	public function getrepeatteleOrders($data = array()) {
		$sql = "SELECT count(*) as num,telephone FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id >= '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_number = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}

		

			$sql .= " GROUP BY telephone HAVING num > 1";
		
		$query = $this->db->query($sql);

		return $query->rows;
	}
	
    public function getrepeatemailOrders($data = array()) {
		$sql = "SELECT count(*) as num,email FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id >= '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_number = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}

		

			$sql .= " GROUP BY email HAVING num > 1";
		
		$query = $this->db->query($sql);

		return $query->rows;
	}
	
	public function getrepeatefirstOrders($data = array()) {
		$sql = "SELECT count(*) as num,firstname FROM `" . DB_PREFIX . "order` o";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "o.order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id >= '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND o.order_number = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}

		

			$sql .= " GROUP BY firstname HAVING num > 1";
		
		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getOrderProducts($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

		return $query->rows;
	}

	public function getOrderOptions($order_id, $order_product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'");

		return $query->rows;
	}

	public function getOrderVouchers($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_voucher WHERE order_id = '" . (int)$order_id . "'");

		return $query->rows;
	}

	public function getOrderVoucherByVoucherId($voucher_id) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order_voucher` WHERE voucher_id = '" . (int)$voucher_id . "'");

		return $query->row;
	}

	public function getOrderTotals($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order");

		return $query->rows;
	}
	
	public function getTotalOrders($data = array()) {
		$sql = "SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order`";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE order_status_id > '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND order_id = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(firstname, ' ', lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND total = '" . (float)$data['filter_total'] . "'";
		}
		if (!empty($data['telephone'])) {
			$sql .= " AND telephone = '" . $data['telephone'] . "'";
		}

		$query = $this->db->query($sql);

		return $query->row['total'];
	}

	public function getTotalOrdersByStoreId($store_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE store_id = '" . (int)$store_id . "'");

		return $query->row['total'];
	}

	public function getTotalOrdersByOrderStatusId($order_status_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE order_status_id = '" . (int)$order_status_id . "' AND order_status_id > '0'");

		return $query->row['total'];
	}

	public function getTotalOrdersByProcessingStatus() {
		$implode = array();

		$order_statuses = $this->config->get('config_processing_status');

		foreach ($order_statuses as $order_status_id) {
			$implode[] = "order_status_id = '" . (int)$order_status_id . "'";
		}

		if ($implode) {
			$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE " . implode(" OR ", $implode));

			return $query->row['total'];
		} else {
			return 0;
		}
	}

	public function getTotalOrdersByCompleteStatus() {
		$implode = array();

		$order_statuses = $this->config->get('config_complete_status');

		foreach ($order_statuses as $order_status_id) {
			$implode[] = "order_status_id = '" . (int)$order_status_id . "'";
		}

		if ($implode) {
			$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE " . implode(" OR ", $implode) . "");

			return $query->row['total'];
		} else {
			return 0;
		}
	}

	public function getTotalOrdersByLanguageId($language_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE language_id = '" . (int)$language_id . "' AND order_status_id > '0'");

		return $query->row['total'];
	}

	public function getTotalOrdersByCurrencyId($currency_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE currency_id = '" . (int)$currency_id . "' AND order_status_id > '0'");

		return $query->row['total'];
	}
	
	public function getTotalSales($data = array()) {
		$sql = "SELECT SUM(total) AS total FROM `" . DB_PREFIX . "order`";

		if (!empty($data['filter_order_status'])) {
			$implode = array();

			$order_statuses = explode(',', $data['filter_order_status']);

			foreach ($order_statuses as $order_status_id) {
				$implode[] = "order_status_id = '" . (int)$order_status_id . "'";
			}

			if ($implode) {
				$sql .= " WHERE (" . implode(" OR ", $implode) . ")";
			}
		} elseif (isset($data['filter_order_status_id']) && $data['filter_order_status_id'] !== '') {
			$sql .= " WHERE order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE order_status_id > '0'";
		}

		if (!empty($data['filter_order_id'])) {
			$sql .= " AND order_id = '" . (int)$data['filter_order_id'] . "'";
		}

		if (!empty($data['filter_customer'])) {
			$sql .= " AND CONCAT(firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
		}

		if (!empty($data['filter_date_added'])) {
			$sql .= " AND DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (!empty($data['filter_date_modified'])) {
			$sql .= " AND DATE(date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
		}

		if (!empty($data['filter_total'])) {
			$sql .= " AND total = '" . (float)$data['filter_total'] . "'";
		}

		$query = $this->db->query($sql);

		return $query->row['total'];
	}
	
	public function createInvoiceNo($order_id) {
		$order_info = $this->getOrder($order_id);

		if ($order_info && !$order_info['invoice_no']) {
			$query = $this->db->query("SELECT MAX(invoice_no) AS invoice_no FROM `" . DB_PREFIX . "order` WHERE invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "'");

			if ($query->row['invoice_no']) {
				$invoice_no = $query->row['invoice_no'] + 1;
			} else {
				$invoice_no = 1;
			}

			$this->db->query("UPDATE `" . DB_PREFIX . "order` SET invoice_no = '" . (int)$invoice_no . "', invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "' WHERE order_id = '" . (int)$order_id . "'");

			return $order_info['invoice_prefix'] . $invoice_no;
		}
	}

	public function getOrderHistories($order_id, $start = 0, $limit = 10) {
		if ($start < 0) {
			$start = 0;
		}

		if ($limit < 1) {
			$limit = 10;
		}

		$query = $this->db->query("SELECT oh.date_added, os.name AS status, oh.comment, oh.notify FROM " . DB_PREFIX . "order_history oh LEFT JOIN " . DB_PREFIX . "order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added DESC LIMIT " . (int)$start . "," . (int)$limit);

		return $query->rows;
	}

	public function getTotalOrderHistories($order_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "order_history WHERE order_id = '" . (int)$order_id . "'");

		return $query->row['total'];
	}

	public function getTotalOrderHistoriesByOrderStatusId($order_status_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "order_history WHERE order_status_id = '" . (int)$order_status_id . "'");

		return $query->row['total'];
	}
	
	public function getEmailsByProductsOrdered($products, $start, $end) {
		$implode = array();

		foreach ($products as $product_id) {
			$implode[] = "op.product_id = '" . (int)$product_id . "'";
		}

		$query = $this->db->query("SELECT DISTINCT email FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_product op ON (o.order_id = op.order_id) WHERE (" . implode(" OR ", $implode) . ") AND o.order_status_id <> '0' LIMIT " . (int)$start . "," . (int)$end);

		return $query->rows;
	}

	public function getTotalEmailsByProductsOrdered($products) {
		$implode = array();

		foreach ($products as $product_id) {
			$implode[] = "op.product_id = '" . (int)$product_id . "'";
		}

		$query = $this->db->query("SELECT COUNT(DISTINCT email) AS total FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_product op ON (o.order_id = op.order_id) WHERE (" . implode(" OR ", $implode) . ") AND o.order_status_id <> '0'");

		return $query->row['total'];
	}
}
